<template>
  <div class="user-container">
    <div class="filter-container">
      <el-input
        v-model="queryParams.username"
        placeholder="请输入用户名"
        clearable
        style="width: 200px"
        class="filter-item"
        @keyup.enter="handleQuery"
      />
      <el-select
        v-model="queryParams.role"
        placeholder="请选择角色"
        clearable
        style="width: 200px"
        class="filter-item"
      >
        <el-option
          v-for="item in roleOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select
        v-model="queryParams.status"
        placeholder="请选择状态"
        clearable
        style="width: 200px"
        class="filter-item"
      >
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" class="filter-item" @click="handleQuery">搜索</el-button>
      <el-button type="success" class="filter-item" @click="handleAdd">添加</el-button>
    </div>

    <el-table v-loading="loading" :data="userList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column label="性别" width="80">
        <template #default="scope">
          <span>{{ scope.row.gender === 0 ? '男' : scope.row.gender === 1 ? '女' : '保密' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="phoneNumber" label="联系电话" width="120" />
      <el-table-column prop="address" label="收货地址" min-width="200" show-overflow-tooltip />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
            {{ scope.row.status === 0 ? '正常' : '冻结' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="角色" width="100">
        <template #default="scope">
          <el-tag :type="roleTypeMap[scope.row.role]">
            {{ roleMap[scope.row.role] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="注册时间" width="180" />
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="userFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialog.type === 'add'">
          <el-input v-model="form.password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
            <el-radio :label="2">保密</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="收货地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入收货地址" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">冻结</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listUser, getUser, addUser, updateUser, delUser } from '@/api/user'

// 查询参数
const queryParams = reactive({
  username: '',
  role: undefined,
  status: undefined
})

// 用户列表数据
const userList = ref([])
const loading = ref(false)

// 角色选项
const roleOptions = [
  { value: 0, label: '用户' },
  { value: 1, label: '门店' },
  { value: 2, label: '管理员' }
]

// 状态选项
const statusOptions = [
  { value: 0, label: '正常' },
  { value: 1, label: '冻结' }
]

// 角色映射
const roleMap = {
  0: '用户',
  1: '门店',
  2: '管理员'
}

// 角色标签类型映射
const roleTypeMap = {
  0: '',
  1: 'warning',
  2: 'danger'
}

// 表单参考
const userFormRef = ref()

// 表单数据
const form = reactive({
  id: undefined,
  username: '',
  password: '',
  gender: 0,
  phoneNumber: '',
  address: '',
  role: 0,
  status: 0
})

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度必须在2到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6到20个字符之间', trigger: 'blur' }
  ],
  phoneNumber: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  role: [{ required: true, message: '请选择用户角色', trigger: 'change' }],
  status: [{ required: true, message: '请选择用户状态', trigger: 'change' }]
}

// 对话框信息
const dialog = reactive({
  visible: false,
  title: '',
  type: ''
})

// 获取用户列表
const getList = async () => {
  loading.value = true
  try {
    const res = await listUser(queryParams)
    userList.value = res || []
  } catch (error) {
    console.error('获取用户列表失败', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  getList()
}

// 重置表单
const resetForm = () => {
  form.id = undefined
  form.username = ''
  form.password = ''
  form.gender = 0
  form.phoneNumber = ''
  form.address = ''
  form.role = 0
  form.status = 0
  userFormRef.value?.resetFields()
}

// 添加按钮操作
const handleAdd = () => {
  resetForm()
  dialog.visible = true
  dialog.title = '添加用户'
  dialog.type = 'add'
}

// 修改按钮操作
const handleUpdate = async (row) => {
  resetForm()
  const id = row.id || row.id
  try {
    const res = await getUser(id)
    Object.assign(form, res)
    dialog.visible = true
    dialog.title = '修改用户'
    dialog.type = 'edit'
  } catch (error) {
    console.error('获取用户详情失败', error)
    ElMessage.error('获取用户详情失败')
  }
}

// 提交表单
const submitForm = async () => {
  userFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          // 修改
          await updateUser(form)
          ElMessage.success('修改成功')
        } else {
          // 新增
          await addUser(form)
          ElMessage.success('新增成功')
        }
        dialog.visible = false
        getList()
      } catch (error) {
        console.error('提交表单失败', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  const id = row.id
  ElMessageBox.confirm('确认要删除该用户吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await delUser(id)
        getList()
        ElMessage.success('删除成功')
      } catch (error) {
        console.error('删除用户失败', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-item {
  margin-right: 10px;
}

.dialog-footer {
  text-align: right;
}
</style>
